package com.wang.auth.controller;


import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sun.xml.internal.bind.v2.TODO;
import com.wang.auth.service.ProcessTemplateService;
import com.wang.common.result.Result;
import com.wang.model.process.ProcessTemplate;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.ResourceUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;

/**
 * <p>
 * 审批模板 前端控制器
 * </p>
 *
 * @author wang
 * @since 2023-04-17
 */
@RestController
@RequestMapping("/admin/process/processTemplate")
public class ProcessTemplateController {

    @Autowired
    private ProcessTemplateService processTemplateService;

    @ApiOperation("获取分页审批模板数据")
    @GetMapping("{page}/{limit}")
    public Result index(@PathVariable Long page, @PathVariable Long limit){
        Page<ProcessTemplate> processTemplatePage = processTemplateService.selectPageProcessTemplate(page,limit);
        return Result.success(processTemplatePage);
    }

    @ApiOperation("上传流程定义")
    @PostMapping("/uploadProcessDefinition")
    public Result uploadProcessDefinition(MultipartFile file){
        /**
         * TODO
         * getPath得到的是构造参数的路径。如果定义时用的是绝对路径，那么使用getPath()返回的结果跟用getAbsolutePath()返回的结果一样
         * getAbsolutePath得到的是全路径。如果构造参数是相对路径，则返回当前目录的绝对路径+构造参数路径，但不会处理“.”和“..”的情况；如果是绝对路径则直接返回
         * getCanonicalPath()返回的是规范化的绝对路径，相当于将getAbsolutePath()中的“.”和“..”解析成对应的正确的路径
         */
        String path = null;
        String filename = file.getOriginalFilename();
        try {
            path = new File(ResourceUtils.getURL("classpath:").getPath()).getAbsolutePath();
        } catch (FileNotFoundException e) {
            throw new RuntimeException(e);
        }
        System.out.println(path);
        File catalogue = new File(path + "/process/");
        if(catalogue.exists()){
            catalogue.mkdirs();
        }
        File zipFile = new File(catalogue + File.separator + filename);
        try {
            file.transferTo(zipFile);
        } catch (IOException e) {
            e.printStackTrace();
            return Result.error("上传失败");
        }
        //根据上传地址后续部署流程定义，文件名称为流程定义的默认key
        HashMap<String, Object> map = new HashMap<>();
        map.put("processDefinitionPath","process/"+filename);
        assert filename != null;
        map.put("processDefinitionKey",filename.substring(0,filename.lastIndexOf(".")));
        return Result.success(map);
    }

//    @PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
    @ApiOperation("新增审批模板")
    @PostMapping("/save")
    public Result save(@RequestBody ProcessTemplate processTemplate){
        processTemplateService.save(processTemplate);
        return Result.success();
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.list')")
    @ApiOperation(value = "修改时回显审批模板数据")
    @GetMapping("get/{id}")
    public Result get(@PathVariable Long id) {
        ProcessTemplate processTemplate = processTemplateService.getById(id);
        return Result.success(processTemplate);
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.templateSet')")
    @ApiOperation("修改审批模板")
    @PutMapping("/update")
    public Result update(@RequestBody ProcessTemplate processTemplate){
        processTemplateService.updateById(processTemplate);
        return Result.success();
    }

    //@PreAuthorize("hasAuthority('bnt.processTemplate.remove')")
    @ApiOperation("删除审批模板")
    @DeleteMapping("/remove/{id}")
    public Result remove(@PathVariable Long id){
        processTemplateService.removeById(id);
        return Result.success("删除成功");
    }

    @ApiOperation("部署流程定义")
    @GetMapping("/publish/{id}")
    public Result publish (@PathVariable Long id){
        processTemplateService.publish(id);
        return Result.success();
    }
}
